package com.hqq.integration.tolerant_reader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Tolerant-Reader是一种整合模式,帮助创建鲁棒通信系统.这种思想对于从其他设备读取信息很宽容。当通信的准则改变时不允许读取者中断
 * <p>
 * 在下面这个例子中我们使用了Java的序列化方式,先通过调用{@link RainbowFishSerializer}中的读写方法,将对象{@link RainbowFish}对象写入到文件中.
 * 之后{@link RainbowFish}演化成{@link RainbowFishV2} 我们中再次使用设计好的方法把它写入文件中,读取端不知道格式发生了改变,还是以之前的方法
 * 读取文件.幸运的是这个读取方法是宽容了,即使写入端的数据发生了改变也不会出现异常
 * Created by heqianqian on 2017/8/18.
 */
public class App {

    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // Write V1
        RainbowFish fishV1 = new RainbowFish("Zed", 10, 11, 12);
        LOGGER.info("fishV1 name={} age={} length={} weight={}", fishV1.getName(),
                fishV1.getAge(), fishV1.getLengthMeters(), fishV1.getWeightTons());
        RainbowFishSerializer.writeV1(fishV1, "fish1.out");
        // Read V1
        RainbowFish deserializedFishV1 = RainbowFishSerializer.readV1("fish1.out");
        LOGGER.info("deserializedFishV1 name={} age={} length={} weight={}",
                deserializedFishV1.getName(), deserializedFishV1.getAge(),
                deserializedFishV1.getLengthMeters(), deserializedFishV1.getWeightTons());
        // Write V2
        RainbowFishV2 fishV2 = new RainbowFishV2("Scar", 5, 12, 15, true, true, true);
        LOGGER.info(
                "fishV2 name={} age={} length={} weight={} sleeping={} hungry={} angry={}",
                fishV2.getName(), fishV2.getAge(), fishV2.getLengthMeters(), fishV2.getWeightTons(),
                fishV2.getHungry(), fishV2.getAngry(), fishV2.getSleeping());
        RainbowFishSerializer.writeV2(fishV2, "fish2.out");
        // Read V2 with V1 method
        RainbowFish deserializedFishV2 = RainbowFishSerializer.readV1("fish2.out");
        LOGGER.info("deserializedFishV2 name={} age={} length={} weight={}",
                deserializedFishV2.getName(), deserializedFishV2.getAge(),
                deserializedFishV2.getLengthMeters(), deserializedFishV2.getWeightTons());
    }
}
